using Microsoft.EntityFrameworkCore;
using RealtimeCollabGame.Application.Interfaces;
using RealtimeCollabGame.Domain.Entities;
using RealtimeCollabGame.Infrastructure.Persistence;

namespace RealtimeCollabGame.Infrastructure.Repositories;

public class PlayerRepository : IPlayerRepository
{
    private readonly GameContext _context;

    public PlayerRepository(GameContext context)
    {
        _context = context;
    }

    public async Task<Player?> GetByIdAsync(Guid id)
    {
        return await _context.Players.FirstOrDefaultAsync(p => p.Id == id);
    }

    public async Task<Player?> GetByNickNameAsync(string nickName)
    {
        return await _context.Players.FirstOrDefaultAsync(p => p.NickName == nickName);
    }

    public async Task<IEnumerable<Player>> GetAllAsync()
    {
        return await _context.Players.ToListAsync();
    }

    public async Task<Player> AddAsync(Player player)
    {
        _context.Players.Add(player);
        await _context.SaveChangesAsync();
        return player;
    }

    public async Task<Player> UpdateAsync(Player player)
    {
        _context.Players.Update(player);
        await _context.SaveChangesAsync();
        return player;
    }

    public async Task DeleteAsync(Guid id)
    {
        var player = await GetByIdAsync(id);
        if (player != null)
        {
            _context.Players.Remove(player);
            await _context.SaveChangesAsync();
        }
    }

    public async Task<bool> ExistsAsync(Guid id)
    {
        return await _context.Players.AnyAsync(p => p.Id == id);
    }

    public async Task<bool> ExistsByNickNameAsync(string nickName)
    {
        return await _context.Players.AnyAsync(p => p.NickName == nickName);
    }
} 